package kubernetes

import (
	"k8s-admin/service/kubernetes"
	"k8s-admin/utils"
	v1 "k8s.io/api/core/v1"
	"time"

	"github.com/gin-gonic/gin"
)

/*根据指定的Namespace获取对应namespace下的Pod*/
func GetK8sClusterPods(ctx *gin.Context) {
	cidStr := ctx.Param("cid")
	params := new(struct {
		Namespace string `json:"namespace" form:"namespace" binding:"required"`
	})
	err := ctx.ShouldBind(params)
	if err != nil {
		utils.ReturnContext(ctx).Failed("失败", err.Error())
	} else {
		pod, err := kubernetes.NewK8sInterface().GetK8sClusterPod(cidStr, params.Namespace)
		if err != nil {
			utils.ReturnContext(ctx).Failed("失败", err.Error())
			return
		}
		var pod_lists []map[string]interface{}
		var PodStatus string
		for _, item := range pod.Items {
			for _, v := range item.Status.ContainerStatuses {
				cpu_usage := item.Spec.Containers[0].Resources.Requests["cpu"]
				mem_usage := item.Spec.Containers[0].Resources.Requests["memory"]
				// 判断Pod运行状态和容器运行状态
				// kubernetes 状态设计的一种“细节陷阱”：Pod 状态是 Running，不代表容器没有问题
				if v.State.Running != nil {
					PodStatus = "Running"
				} else if v.State.Waiting != nil {
					PodStatus = v.State.Waiting.Message
				} else if v.State.Terminated != nil {
					PodStatus = v.State.Terminated.Reason
				} else if item.Status.Phase == v1.PodPending {
					PodStatus = "Pending"
				}
				// 检查是否为 BackOff 状态
				if v.State.Waiting != nil && (v.State.Waiting.Reason == "CrashLoopBackOff" || v.State.Waiting.Reason == "ImagePullBackOff") {
					PodStatus = v.State.Waiting.Reason
				}
				pod_lists = append(pod_lists, map[string]interface{}{
					"namespace": item.Namespace,

					"pod_name":    item.Name,
					"cpu_usage":   cpu_usage,
					"mem_usage":   mem_usage,
					"labels":      item.Labels,
					"create_time": item.CreationTimestamp.Time.Format(time.DateTime),
					"rest_count":  v.RestartCount,
					"pod_ip":      item.Status.PodIP,
					"status":      PodStatus,
				})
			}

		}
		utils.ReturnContext(ctx).Successful("成功", pod_lists)
	}
}

/*根据namespace+podName查看对应pod详情*/
func GetK8sClusterNamePod(ctx *gin.Context) {
	params := new(struct {
		Namespace string `json:"namespace" form:"namespace" binding:"required"`
		PodName   string `json:"pod_name" form:"pod_name" binding:"required"`
	})
	cid := ctx.Param("cid")
	err := ctx.ShouldBind(&params)
	if err != nil {
		utils.ReturnContext(ctx).Failed("失败", err.Error())
	} else {
		pod, err := kubernetes.NewK8sInterface().GetK8sClusterNamePod(cid, params.Namespace, params.PodName)
		if err != nil {
			utils.ReturnContext(ctx).Failed("失败", err.Error())
			return
		}
		utils.ReturnContext(ctx).Successful("成功", pod)
	}
}

/*删除指定Namespace下的某个Pod*/
func DeleteK8sClusterPod(ctx *gin.Context) {
	cid := ctx.Param("cid")
	params := new(struct {
		Namespace string `json:"namespace" form:"namespace" binding:"required"`
		PodName   string `json:"pod_name" form:"pod_name" binding:"required"`
	})
	err := ctx.ShouldBind(params)
	if err != nil {
		utils.ReturnContext(ctx).Failed("失败", err.Error())
	} else {
		err := kubernetes.NewK8sInterface().DeleteK8sClusterPod(cid, params.Namespace, params.PodName)
		if err != nil {
			utils.ReturnContext(ctx).Failed("失败", err.Error())
			return
		}
		utils.ReturnContext(ctx).Successful("成功", params.PodName+"删除成功")
	}
}

/*查看指定Namespace下的某个Pod的日志信息*/
func GetK8sClusterPodLogs(ctx *gin.Context) {
	cid := ctx.Param("cid")
	params := new(struct {
		Namespace     string `json:"namespace" form:"namespace" binding:"required"`
		PodName       string `json:"pod_name" form:"pod_name" binding:"required"`
		ContainerName string `json:"container" form:"container_name"`
	})
	err := ctx.ShouldBind(params)
	if err != nil {
		utils.ReturnContext(ctx).Failed("失败", err.Error())
	} else {
		logs, err := kubernetes.NewK8sInterface().GetK8sClusterPodLogs(cid, params.Namespace, params.PodName, params.ContainerName)
		if err != nil {
			utils.ReturnContext(ctx).Failed("失败", err.Error())
			return
		}
		utils.ReturnContext(ctx).Successful("成功", logs)

	}
}

/*查看指定Namespace下的某个Pod Yaml内容*/
//func GetK8sClusterPodYaml(ctx *gin.Context) {
//	cid := ctx.Param("cid")
//	params := new(struct {
//		Namespace string `json:"namespace" form:"namespace" binding:"required"`
//		PodName   string `json:"pod_name" form:"pod_name" binding:"required"`
//	})
//	err := ctx.ShouldBind(params)
//	if err != nil {
//		utils.ReturnContext(ctx).Failed("失败", err.Error())
//	} else {
//		yaml, err := kubernetes.NewK8sInterface().GetK8sClusterPodYaml(cid, params.Namespace, params.PodName)
//		if err != nil {
//			utils.ReturnContext(ctx).Failed("失败", err.Error())
//			return
//		}
//		utils.ReturnContext(ctx).Successful("成功", yaml)
//
//	}
//}

/*更新Pod*/
//func UpdateK8sClusterPodLogs(ctx *gin.Context) {}

/*获取Pod 容器*/
func GetK8sClusterPodContainer(ctx *gin.Context) {
	cid := ctx.Param("cid")
	params := new(struct {
		Namespace string `json:"namespace" form:"namespace" binding:"required"`
		PodName   string `json:"pod_name" form:"pod_name" binding:"required"`
	})
	err := ctx.ShouldBind(params)
	if err != nil {
		utils.ReturnContext(ctx).Failed("失败", err.Error())
	} else {
		container_name, err := kubernetes.NewK8sInterface().GetK8sClusterPodContainer(cid, params.Namespace, params.PodName)
		if err != nil {
			utils.ReturnContext(ctx).Failed("失败", err.Error())
			return
		}
		utils.ReturnContext(ctx).Successful("成功", container_name)

	}
}


// 通过图形界面创建Pod
